from flask import render_template, Blueprint, request
from apps.pojo.Entity import User,UserSchema,db
from apps.util.LayData import LayData

user_bp = Blueprint('user', __name__, url_prefix='/user')
user_schema = UserSchema(many=True)

@user_bp.route('/tolist')
def tolist():
    return render_template('user/list.html')


@user_bp.route('/list', methods=['GET','POST'])
def list():
    # 接收分页参数   page 当前页  limit 每页显示的条数
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 10, type=int)
    # 查询用户表 的记录数
    count = User.query.count()
    # 查询用户集合数据
    offset = (page - 1) * limit
    userList = User.query.offset(offset).limit(limit).all()
    # 将集合里面的对象转换为字典
    users = user_schema.dump(userList)
    # 构造layui格式json对象
    return {
        "code": 0,
        "msg": "查询成功",
        "count": count,
        "data": users
    }


@user_bp.route('/toadd')
def toadd():
    return render_template('user/add.html')

@user_bp.route('/addSave', methods=['POST'])
def addSave():
    param = request.form
    user = User()
    user.username = param.get('username')
    user.password = param.get('password')
    user.sex = param.get('sex')
    try:
        # 保存用户到数据库
        db.session.add(user)
        # 提交事务
        db.session.commit()
        # 返回json数据
        return LayData.data2(200, '添加成功')
    except Exception as e:
        db.session.rollback()
        return LayData.data2(500, '添加失败')


@user_bp.route('/toupdate/<int:id>')
def toUpdate(id):
    user = User.query.filter(User.id == id).first()
    return render_template('user/edit.html', user=user)


@user_bp.route('/updateSave', methods=['POST'])
def updateSave():
    param = request.form
    id = param.get('id')
    user = User.query.filter(User.id == id).first()
    user.username = param.get('username')
    user.password = param.get('password')
    # user.sex = param.get('sex')
    try:
        db.session.commit()
        return LayData.data2(200, '修改成功')
    except Exception as e:
        db.session.rollback()
        return LayData.data2(500, '修改失败')


@user_bp.route('/delete', methods=['POST'])
def delete():
    id = request.form.get('id')
    user = User.query.filter(User.id == id).first()
    try:
        # 删除用户
        db.session.delete(user)
        # 提交事务
        db.session.commit()
        # 返回json数据
        return LayData.data2(200, '删除成功')
    except Exception as e:
        db.session.rollback()
        return LayData.data2(500, '删除失败')